package net.ankao.job.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import net.ankao.job.configuration.QuartzAutoConfiguration;
import net.ankao.job.entity.AkApplicationJob;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Scheduler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 客户端管理
 *
 * @author LILU
 * @date 2024-11-28 11:00
 */
@Component
public class ClientJobManager {

    @Resource
    private Scheduler scheduler;

    @Resource
    private QuartzAutoConfiguration quartzAutoConfiguration;


    public void start() throws Exception {
        // 启动调度器
        scheduler.start();
    }

    public void addDynamicJob(AkApplicationJob applicationJob) throws Exception {
        String paramsStr = applicationJob.getParamsStr();
        Map<String, Object> parameter = new HashMap<>();
        if (StringUtils.isNotEmpty(paramsStr)) {
            parameter = JSON.parseObject(paramsStr, new TypeReference<Map<String, Object>>() {
            });
        }
        parameter.put(Constant.APPLICATION_JOB_KEY,applicationJob);
        quartzAutoConfiguration.addJob(scheduler, applicationJob.getId(), applicationJob.getApplicationName(), applicationJob.getCronStr(), parameter);
    }

    public void deleteDynamicJob(AkApplicationJob applicationJob) throws Exception {
        quartzAutoConfiguration.deleteJob(scheduler, applicationJob.getId(), applicationJob.getApplicationName());
    }

    public void rescheduleDynamicJob(AkApplicationJob applicationJob) throws Exception {
        String paramsStr = applicationJob.getParamsStr();
        Map<String, Object> parameter = new HashMap<>();
        if (StringUtils.isNotEmpty(paramsStr)) {
            parameter = JSON.parseObject(paramsStr, new TypeReference<Map<String, Object>>() {
            });
        }
        parameter.put(Constant.APPLICATION_JOB_KEY,applicationJob);
        quartzAutoConfiguration.rescheduleJob(scheduler, applicationJob.getId(), applicationJob.getApplicationName(), applicationJob.getCronStr(), parameter);
    }
}
